package com.shawn.baseappbygroovydsl.ui.views

import android.Manifest
import android.animation.ObjectAnimator
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import com.bumptech.glide.request.transition.Transition
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.target.CustomTarget
import com.choryan.quan.videowzproject.extension.ExtensionView.expandTouchView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.shawn.baseappbygroovydsl.MainActivity
import com.shawn.baseappbygroovydsl.R
import com.shawn.baseappbygroovydsl.appInterface.IPopBtnActionListener
import com.shawn.baseappbygroovydsl.bean.BeanUserLocal
import com.shawn.baseappbygroovydsl.component.CountDownTimer
import com.shawn.baseappbygroovydsl.databinding.FragmentEffectBinding
import com.shawn.baseappbygroovydsl.dialog.DialogBase
import com.shawn.baseappbygroovydsl.net.Api
import com.shawn.baseappbygroovydsl.net.ApiCallback
import com.shawn.baseappbygroovydsl.pop.PopWechat50RewardVideo
import com.shawn.baseappbygroovydsl.ui.adapter.AutoHeightPagerAdapter
import com.shawn.baseappbygroovydsl.ui.base.FragmentBase
import com.shawn.baseappbygroovydsl.ui.extension.ExtensionCommon.toast
import com.shawn.baseappbygroovydsl.ui.extension.ExtensionLog.log
import com.shawn.baseappbygroovydsl.utils.ExtensionCommon.dp
import com.shawn.baseappbygroovydsl.utils.UtilCalendar
import com.shawn.baseappbygroovydsl.utils.UtilHundredContribute
import com.shawn.baseappbygroovydsl.utils.UtilPermissions
import com.shawn.baseappbygroovydsl.utils.UtilScriptExplorer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import retrofit2.Response
import kotlin.coroutines.resume

class EffectFragment : FragmentBase<FragmentEffectBinding>(R.layout.fragment_effect),
    DialogBase.IDialogActionListener, IPopBtnActionListener {
    private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
    var job: Job? = null
    private lateinit var slideshowViewModel: ViewModel
    private var mAdapter: AutoHeightPagerAdapter? = null
    private var isRequestLocationFirst = true
    private val locationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            // 前台定位权限已授予

        } else {
            // 用户拒绝
            isRequestLocationFirst = false
        }
    }

    private val dialogLoginWechat by lazy {
        val value = PopWechat50RewardVideo(requireContext())
        value.iPopBtnActionListener = this
        value
    }

    private val launcher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        var result = false
        permissions.entries.forEach {
            result = it.value
            "EXTERNAL ${it.key} = ${it.value}".log()
        }
    }

    override fun statusBar() {

    }

    override fun lazyLoad() {
        slideshowViewModel = ViewModelProvider(this)[NestedViewModel::class.java]
        initView()
    }

    override fun initClick() {

    }

    override fun onKeyCodeBack(): Boolean {
        return false
    }

    private fun initView() {
        showCashDialog()
        effect1()
        effect2()
        effect3()
        effect4()
        goNextFrag()
        effectGuide()
        effectStartRotation()
        showDialog()
        initAutoHeightViewPager()
        viewDelegate()
        downTimer()
        insertCalendar()
        getLocalNet()
        getDeviceState()
        downTimer2()
        stripedProgressBar()
    }

    private fun showCashDialog() {
        var index = 0
        mBind.btnCash.setOnClickListener {
            dialogLoginWechat.show(mBind.root, index)
            index += 1
            if (index > 3) {
                index = 0
            }
        }
    }

    private fun effect3() {

    }

    private fun effect1() {

    }

    private fun effect2() {

    }

    private fun effect4() {
        mBind.btn1.setOnClickListener {
            mBind.scratchView.reset()
        }
    }

    private fun goNextFrag() {
        mBind.btnGoNextFrag.setOnClickListener {
            showSubFrag(
                SecondFragment::class.java.name,
                SecondFragment.newInstance(),
                R.id.fl_frag_sub_container,
                R.anim.anim_drama_show
            )
        }
    }

    private fun effectGuide() {
        mBind.btnGoGuide.setOnClickListener {
            showSubFrag(
                SecondFragment::class.java.name,
                SecondFragment.newInstance(),
                R.id.fl_frag_sub_container,
                R.anim.anim_drama_show
            )
        }
    }

    private fun effectStartRotation() {
        val rotateAnimation = RotateAnimation(
            0f, 360f, // 从0度旋转到360度
            Animation.RELATIVE_TO_SELF, 0.5f, // 旋转中心X（相对于自身宽度的50%）
            Animation.RELATIVE_TO_SELF, 0.5f  // 旋转中心Y（相对于自身高度的50%）
        ).apply {
            duration = 2000L // 设置动画持续时间（毫秒）
            repeatCount = Animation.INFINITE // 设置无限循环
            interpolator = LinearInterpolator() // 设置线性插值器
            fillAfter = true // 动画结束后保持最后状态
        }

        // 开始动画
//        mBind.ivLoad.startAnimation(rotateAnimation)

        // 创建旋转动画
        val rotateAnimator =
            ObjectAnimator.ofFloat(mBind.ivLoad, "rotation", 0f, 360f).apply {
                duration = 2000 // 设置动画持续时间
                repeatCount = ObjectAnimator.INFINITE // 设置循环
                repeatMode = ObjectAnimator.RESTART // 设置循环模式
                interpolator = LinearInterpolator() // 设置线性插值器，确保匀速旋转
            }

        // 开始动画
        rotateAnimator.start()
    }

    private fun showDialog() {
        mBind.btnDialog.setOnClickListener {
            lifecycleScope.launch {
                showDialog("签到活动", "签到领10000币") // 直到dialog被关闭, 才会继续运行下一行
                showDialog("新手任务", "做任务领20000币") // 直到dialog被关闭, 才会继续运行下一行
                showDialog("首充奖励", "首充6元送神装")
            }
        }
    }

    private fun initAutoHeightViewPager() {
        val viewList: MutableList<View> = ArrayList()
        viewList.add(LayoutInflater.from(requireContext()).inflate(R.layout.view_demo_1, null))
        viewList.add(LayoutInflater.from(requireContext()).inflate(R.layout.view_demo_2, null))

        mBind.viewpager.setAdapter(AutoHeightPagerAdapter().also { mAdapter = it })
        mAdapter?.setViews(viewList)
        mBind.viewpager.setCurrentItem(1)
    }

    private fun viewDelegate() {
        mBind.viewDelegate.run {
            expandTouchView(30f.dp.toInt())
            setOnClickListener {
                "通过TouchDelegate扩大点击区域".toast()
            }
        }
    }

    private fun downTimer() {
        val timerDown = CountDownTimer(60, 1000)
        mBind.btnDownTimer.setOnClickListener {
            timerDown.start(object : CountDownTimer.OnTimerCallBack {
                override fun onStart() {

                }

                override fun onTick(times: Int) {
                    mBind.tvDownTimer.text = "$times"
                }

                override fun onFinish() {

                }

            })
        }
    }

    private fun insertCalendar() {
        mBind.btnCalendar.setOnClickListener {
            UtilCalendar.requestCalendarPermission(requireActivity() as MainActivity) {
                if(it) {
                    UtilCalendar.sendRemind(requireContext()) { result ->
                        when (result) {
                            0 -> {
                                "提醒成功".log()
                            }
                            -1 -> {
                                "签到提醒发送失败".toast()
                            }
                            -2 -> {
                                "请进入设置开启日历权限".toast()
                            }
                        }
                    }
                } else {
                    "请进入设置开启日历权限".toast()
                }
            }
        }
    }

    private fun getLocalNet() {
        mBind.btnNet.setOnClickListener {
            Api.apiService.getUserLocal().enqueue(object : ApiCallback<BeanUserLocal> {
                override fun onComplete() {

                }

                override fun success(response: Response<BeanUserLocal>?) {
                    super.success(response)
                    response?.body()?.let {
                        if (it.code == 200 && it.country.contains("中国")) {
                            it.log()
                            mBind.tvLoacl.post {
                                mBind.tvLoacl.text = "$it"
                            }
                        }
                    }
                }

                override fun error(response: Response<*>?, t: Throwable?) {
                    super.error(response, t)

                }
            })
        }
    }

    private fun getDeviceState() {
        val activity = requireActivity()
        val accessAbilityRunning = UtilScriptExplorer.isAccessibilityRunning(activity)
        val isUSBConnected = UtilScriptExplorer.isUSBConnected(activity)
        val isInDevMode = UtilScriptExplorer.isInDevMode(activity)
        val isEmulator = UtilScriptExplorer.isEmulator(activity)
        val isRoot = UtilScriptExplorer.isRoot(activity)
        "accessAbilityRunning=$accessAbilityRunning isUSBConnected=$isUSBConnected isInDevMode=$isInDevMode isEmulator=$isEmulator isRoot=$isRoot".log()
    }

    private fun downTimer2() {
        val times = 30
        initJob(times)
        mBind.btnDownTimer2.setOnClickListener {
            job?.cancel()
            job = null
            initJob(times)
            job?.start()
        }
    }

    private fun stripedProgressBar() {
        mBind.btnStripedProgressBar.setOnClickListener {
            coroutineScope.launch {
                repeat(101) {
                    delay(5)
                    "stripedProgressBar $it".log()
                    mBind.stripedProgressBar.progress = it
                }
            }
        }
    }
    private fun initJob(times: Int) {
        if (job == null) {
            job = coroutineScope.launch {
                repeat(times) { _times ->
                    "倒计时：${_times}".log()
                    mBind.tvDownTimer2.text = "${times - _times}s后自动解锁并领取"
                    delay(1 * 1000)
                }
            }
        }
    }

    private suspend fun showDialog(title: String, content: String) = suspendCancellableCoroutine { continuation ->
        MaterialAlertDialogBuilder(requireContext())
            .setTitle(title)
            .setMessage(content)
            .setPositiveButton("我知道了") { dialog, _ ->
                dialog.dismiss()
            }
            .setOnDismissListener {
                continuation.resume(Unit)
            }
            .show()
    }


    override fun getData() {
        refreshHistory()
    }

    private fun loadUserIcon(view:View) {
        val tv = view as TextView
        tv.compoundDrawablePadding = 0.0f.dp.toInt()
        val size = 15f.dp.toInt()
        Glide.with(requireActivity()).load(UtilHundredContribute.curIcon()).override(size,size).transform(CircleCrop()).into(object :
            CustomTarget<Drawable>(){
            override fun onResourceReady(
                resource: Drawable,
                transition: Transition<in Drawable>?
            ) {
                tv.setCompoundDrawablesWithIntrinsicBounds(resource, null, null, null)
                tv.compoundDrawablePadding = 5.0f.dp.toInt()
            }

            override fun onLoadCleared(placeholder: Drawable?) {

            }
        })
    }

    override fun getBind(view: View): FragmentEffectBinding {
        return FragmentEffectBinding.bind(view)
    }

    private fun refreshHistory() {

    }

    fun checkLocationPermission() {
        val context1 = activity ?: return
        val hasLocationPermission = UtilPermissions.hasForegroundLocationPermission(context1)
        if (!hasLocationPermission) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(context1, Manifest.permission.ACCESS_FINE_LOCATION) && !isRequestLocationFirst) {
                // 检查是否 "不再询问"0
                return
            }
            val isRequestLocationPermission = true
            "checkLocationPermission isRequestLocationPermission = $isRequestLocationPermission hasLocationPermission = $hasLocationPermission".log()
            if (isRequestLocationPermission) {
                locationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
            }
        } else {
            "checkLocationPermission 不需要获取定位权限".log()
        }
    }

    fun checkStoragePermission() {
        val requestList = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        launcher.launch(requestList)
    }

    companion object {
        const val type1 = "type"
        fun newInstance(): EffectFragment {
            val args = Bundle()
            val fragment = EffectFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onDialogActionListener(position: String, params: Any?) {

    }

    override fun onPopActionClick(position: String, params: Any?) {

    }
}